#include "qserialbase.h"

QSerialBase::QSerialBase()
 : QIODevice()
{
    SetSerialName(1);
    construct();
}

QSerialBase::QSerialBase(int iPort):
    QIODevice()
{
    SetSerialName(iPort);
    construct();
}

QSerialBase::~QSerialBase()
{
    delete m_pMutex;
}


void QSerialBase::SetSerialName(int iPort)
{
#ifdef _TTY_WIN_
    m_strSerialName.sprintf("COM%d",iPort);
#elif defined(_TTY_IRIX_)
    m_strSerialName.sprintf("/dev/ttyf%d",iPort);

#elif defined(_TTY_HPUX_)
    m_strSerialName.sprintf("/dev/tty%dp0",iPort);

#elif defined(_TTY_SUN_)
    m_strSerialName.sprintf("/dev/tty%c",iPort+"a"-1);

#elif defined(_TTY_DIGITAL_)
    m_strSerialName.sprintf("/dev/tty%02d",iPort);

#elif defined(_TTY_FREEBSD_)
    m_strSerialName.sprintf("/dev/ttyd%d",iPort);

#else
    m_strSerialName.sprintf("/dev/ttyS%d",iPort-1);
#endif
}

QString QSerialBase::SerialName()
{
    return m_strSerialName;
}

void QSerialBase::construct()
{
    m_PortSettings.BaudRate=BAUD9600;
    m_PortSettings.DataBits=DATA_8;
    m_PortSettings.Parity=PAR_NONE;
    m_PortSettings.StopBits=STOP_1;
    m_PortSettings.FlowControl=FLOW_HARDWARE;
    m_PortSettings.Timeout_Millisec=500;
    m_pMutex = new QMutex( QMutex::Recursive );
    setOpenMode(QIODevice::NotOpen);
}

void QSerialBase::setQueryMode(QueryMode mode)
{
    _queryMode = mode;
}

BaudRateType QSerialBase::baudRate() const
{
    return m_PortSettings.BaudRate;
}

DataBitsType QSerialBase::dataBits() const
{
    return m_PortSettings.DataBits;
}

ParityType QSerialBase::parity() const
{
    return m_PortSettings.Parity;
}

StopBitsType QSerialBase::stopBits() const
{
    return m_PortSettings.StopBits;
}

FlowType QSerialBase::flowControl() const
{
    return m_PortSettings.FlowControl;
}

bool QSerialBase::isSequential() const
{
    return true;
}

bool QSerialBase::atEnd() const
{
    if (size()) {
        return true;
    }
    return false;
}

qint64 QSerialBase::readLine(char * data, qint64 maxSize)
{
    qint64 numBytes = bytesAvailable();
    char* pData = data;

    if (maxSize < 2)
        return -1;
   while (pData<(data+numBytes) && --maxSize) {
        readData(pData, 1);
        if (*pData++ == '\n') {
            break;
        }
    }
    *pData='\0';
    return (pData-data);
}

ulong QSerialBase::lastError() const
{
    return m_ulLastErr;
}
